import AJAX from '@/common/ajax'
import { isLogin } from '@/utils'

export const LOGIN = 'LOGIN'
export const VERIFY = 'VERIFY'
export const USER_INFO = 'USER_INFO'

const userid = isLogin()

export default {
  namespaced: true,
  state: {
    login: '',
    verify: '',
    userinfo: {}
  },
  mutations: {
    [LOGIN](state, { data, params }) {
      state.login = data
      console.log('state.login', state.login)
    },
    [USER_INFO](state, data) {
      state.userinfo[userid] = data
      console.log('state.userinfo', state.userinfo[userid])
    },
    [VERIFY](state, data) {
      state.verify = data
      console.log('state.verify', state.verify)
    }
  },
  actions: {
    async login({ commit, state }, params) {
      let [err, data] = await AJAX({
        name: 'login',
        method: 'POST',
        data: {
          user_name: params.username,
          user_password: params.password,
          validate: params.code,
          key: params.key
        }
      })
      commit(LOGIN, data)
      return data
    },
    async userInfo({ commit, state }) {
      const data = state.userinfo[userid]
      if (data) {
        return data
      } else {
        let [err, data] = await AJAX({
          name: 'getuserinfo',
          header: true
        })
        commit(USER_INFO, data)
        return data
      }
    },
    async verify({ commit, state }) {
      let [err, data] = await AJAX({
        name: 'verify'
      })
      commit(LOGIN, data)
      return data
    }
  }
}
